﻿using System;
using System.Collections.Concurrent;
using System.Threading;
using xinhyue.game.client.frame.stream;

public class ServerMessageDispatch
{
    private ConcurrentDictionary<int, MessageMappingInfo> cache = new ConcurrentDictionary<int, MessageMappingInfo>();

    public ConcurrentDictionary<int, PushMessageInfo> pushCallback = new ConcurrentDictionary<int, PushMessageInfo>();

    public void AddPushMessageCallback(int messageId, PushMessageInfo pushMessageInfo)
    {
        pushCallback.TryAdd(messageId, pushMessageInfo);
    }
    private PushMessageInfo GetPushCallback(int messageId)
    {
        PushMessageInfo value;
        pushCallback.TryGetValue(messageId, out value);
        return value;

    }

    public void AddRequestMappingCache(MessageMappingInfo messageMappingInfo)
    {
        int clienSeqID = messageMappingInfo.ClientSeqID;
        cache.TryAdd(clienSeqID, messageMappingInfo);
    }

    public MessageMappingInfo DeMessageMapping(int clientSeqID)
    {
        MessageMappingInfo messageMappingInfo;
        cache.TryRemove(clientSeqID, out messageMappingInfo);
        return messageMappingInfo;
    }

    public void DispatchMessage(ByteBuf byteBuf)
    {
        byteBuf.MarkReaderIndex();
        byteBuf.SkipBytes(4);//跳过包的总大小字节
        int clientSeqID = byteBuf.ReadInt();
        byteBuf.SkipBytes(20);
        EnumMessageType messageType = (EnumMessageType)byteBuf.ReadByte();
        byteBuf.ResetReaderIndex();
        if (messageType == EnumMessageType.RESPONSE)
        {
            MessageMappingInfo messageMappingInfo = this.DeMessageMapping(clientSeqID);
            if (messageMappingInfo != null)
            {
                IGameMessage responseMessage = messageMappingInfo.ResponseMessage;
              
                //读取响应信息
                CodecFactory.DecodeMessage(byteBuf, responseMessage);
                messageMappingInfo.Action.Invoke(responseMessage);
            }
        }
        else if (messageType == EnumMessageType.PUSH)
        {
            int messageId = byteBuf.ReadInt();
            PushMessageInfo pushMessageInfo = this.GetPushCallback(messageId);
            if (pushMessageInfo != null)
            {
                IGameMessage gameMessage = (IGameMessage)Activator.CreateInstance(pushMessageInfo.GameMessageType);
                gameMessage.GetHeader().Read(byteBuf);
                CodecFactory.DecodeMessage(byteBuf, gameMessage);
                pushMessageInfo.Callback.Invoke(gameMessage);

            }
        }
    }



}



